package com.tssup.fesco.common.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.BucketInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * OSS工具类
 *
 * @author shuchang.liao
 * @create 2017-05-15 11:21
 */
public class OSSUtil
{
    private static Logger logger= LoggerFactory.getLogger(OSSUtil.class);
    /**
     * 获取对应的访问地址(url)
     *
     * @param client
     *            OSS客户端对象
     * @param bucketName
     *            Bucket名称
     * @param key
     *            对象在OSS服务器上存储的路径，可包括子文件夹的路径；例如item/item_100101.jpg
     * @return 返回对象的访问地址
     */
    public static String getUrl(OSSClient client, String bucketName, String key)
    {
        StringBuffer url = new StringBuffer();
        url.append("http://");
        url.append(bucketName);
        url.append(".");
        url.append(client.getEndpoint().toString().replaceAll("http://", ""));
        url.append("/");
        url.append(key);

        return url.toString();
    }

    /**
     * 判断Bucket是否存在，否 则创建Bucket
     * @param ossClient
     * @param bucketName
     * @return
     */
    public static BucketInfo getBuckInfo(OSSClient ossClient,String bucketName){
        if (ossClient.doesBucketExist(bucketName)) {
            logger.info("您已经创建Bucket：" + bucketName + "。");
        } else {
            logger.info("您的Bucket不存在，创建Bucket：" + bucketName + "。");
            // 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
            // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
            ossClient.createBucket(bucketName);
        }

        // 查看Bucket信息。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
        // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
        BucketInfo info = ossClient.getBucketInfo(bucketName);
       /* System.out.println("Bucket " + bucketName + "的信息如下：");
        System.out.println("\t数据中心：" + info.getBucket().getLocation());
        System.out.println("\t创建时间：" + info.getBucket().getCreationDate());
        System.out.println("\t用户标志：" + info.getBucket().getOwner());*/
        return info;
    }
}
